package org.ihelpuoo.weboo.upload.index;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.ihelpuoo.core.Factory;
import org.ihelpuoo.core.Nut;
import org.ihelpuoo.io.FileUtils;
import org.ihelpuoo.lang.NutException;
import org.ihelpuoo.util.Properties;

public class IndexMakerFactory extends Factory
{
	public static IndexMakerFactory me(Nut nut) throws NutException
	{
		return (IndexMakerFactory)nut.getFactory("upload/IndexMaker.properties");
	}

	private Map<String, IndexMaker>	makers;
	private IndexMaker				defaultMaker;

	@Override
	public void init(Properties config) throws NutException
	{
		super.init(config);
		makers = new HashMap<String, IndexMaker>();
		Iterator<String> it = config.keySet().iterator();

		while (it.hasNext())
		{
			String key = it.next();
			if ("class".equals(key))
				continue;
			try
			{
				IndexMaker maker = (IndexMaker)Class.forName(config.getStringTrimed(key))
						.newInstance();
				if ("default".equals(key))
					defaultMaker = maker;
				else
					makers.put(key,maker);
			}
			catch (Exception e)
			{
				throw new NutException("Fail to create make: " + config.getStringTrimed(key));
			}
		}

	}

	public IndexMaker getMaker(String name)
	{
		if (null == name)
			return defaultMaker;
		IndexMaker maker = makers.get(name.toLowerCase());
		if (null == maker)
			return defaultMaker;
		return maker;
	}

	public IndexMaker getMaker(File f)
	{
		return this.getMaker(FileUtils.getExtension(f));
	}

	public IndexMaker getDefaultMaker()
	{
		return defaultMaker;
	}

	@Override
	public void depose() throws NutException
	{
	}

}
